<!Doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>进度条测试</title>
    <script type="text/javascript" src="./js/jquery-1.10.1.min.js"></script>
</head>
<body>

<input type="file" id="file_upload"/>
<input type="button" value="上传" id="upload"/>
<div style="background:#848484;width:100px;height:10px;margin-top:5px">
    <div id="progressNumber" style="background:#428bca;width:0px;height:10px">
    </div>
</div>
<font id="percent">0%</font>
</body>
<script>
    var file = null;
    $(function () {
        $("#upload").click(function () {
//            file = readBlob(10, 100);
            upload();
        });
    });
    var input = document.getElementById("file_upload");

    //文件域选择文件时, 执行readFile函数
    input.addEventListener('change', readFile, false);

    function readFile() {
        file = this.files[0].slice(5233);
    }
    //上传文件
    function upload() {
        var xhr = new XMLHttpRequest();

        var fd = new FormData();

        fd.append("fileName", file);

        //监听事件
        xhr.upload.addEventListener("progress", uploadProgress, false);

        //发送文件和表单自定义参数
        xhr.open("POST", "/UploadServlet", true);

        xhr.send(fd);
    }

    function uploadProgress(evt) {
        console.log(evt);
        console.log(evt.loaded + ' - ' + evt.total);
        console.log(navigator.onLine);
        if (evt.lengthComputable) {
            //evt.loaded：文件上传的大小 evt.total：文件总的大小
            var percentComplete = Math.round((evt.loaded) * 100 / evt.total);
            //加载进度条，同时显示信息
            $("#percent").html(percentComplete + '%');
            $("#progressNumber").css("width", "" + percentComplete + "px");
        }
    }

    /* 分段传输 */
    function readBlob(start, end) {
        var files = document.getElementById('file_upload').files;

        if (!files.length) return false;

        var file = files[0], start = parseInt(start, 10) || 0, end = parseInt(end, 10) || (file.size - 1);

        var reader = new FileReader();

        reader.onload = function (e) {
            console.log("Read bytes: " + (start + 1) + " - " + (end + 1) + " of " + file.size + " bytes");
            console.log(e);
        };

        var blob;
        if (file.webkitSlice) {
            blob = file.webkitSlice(start, end + 1);
        } else if (file.mozSlice) {
            blob = file.mozSlice(start, end + 1);
        } else if (file.slice) {
            blob = file.slice(start, end + 1);
        }

        return blob;
    }

</script>
</html>